package com.richman.controller;

import com.richman.hg.HGHttp;
import com.richman.hg.HGThread;
import com.richman.hgps38.HGPS38EventManager;
import com.richman.hgps38.HGPS38MergeThread;
import com.richman.hgps38.ServerThread;
import com.richman.isn.ISNThread;
import com.richman.ps38.PS38Thread;
import com.richman.ps38.entity.SendData;
import com.richman.view.MainWindow;
import com.richman.view.SettingPane;

import team.gl.nio.cln.NettyClient;
import team.gl.nio.isncln.ISNNettyClient;
import team.gl.nio.isnhgcln.ISNHGNettyClient;

import java.awt.BorderLayout;

import java.awt.Button;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.TextField;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.util.Date;
import java.util.Vector;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.text.SimpleDateFormat;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;


public class DecreaseRatioClient {
	
	public static boolean bStartEngine = false;
	
	public static long startEngineTime = 0;
	
	public static PS38Thread ps38Thread = null;
	
	static HGThread hgThread = null;
	
	static ISNThread isnThread = null;
	
	public static BetThread betThread = null; 
	
	public static boolean useForOriginal = true;
	
	public static boolean isInbet = false;
	
	public static boolean isInManualRebet = false;
	
	static HGPS38MergeThread hgps38MergeThread = null;
	
	public static boolean hasIllegalBet = false;
	
	public static boolean hasSpecialIllegalBet = false;
	
	public static JButton btnpData;
	
	public static JButton btnConnect;
	
	public static boolean bNeg = false;
	
	public  boolean blogTofile = true;
	
	public static BetCentralManager betCtrMng = null;
	
	static ServerThread serverThread = null;
	
	public static Button btnPMergeWnd;
	
	public static Button btnbetlist;
	
	public static Button btnNewPMergeWnd;
	
	public static Button btnPP8Wnd;
	
	public static Button btnPHGWnd;
	
	public static Button btnPZhiboWnd;
	
	public static Button btnZhiboConnect;
	
	public static Button btnMergeWnd;
	
	public static Button btnNewMergeWnd;
	
	public static Button btnChangepw;
	
	public static boolean connected = false;
	
	public static boolean zhiboConnected = false;
	
	
	
	public static boolean showMergeWnd = false;
	public static boolean showP8 = false;
	
	public static boolean showhg = false;
	public static boolean showZhibo = false;
	

	
	public static DecreaseRatioClient sa;
	
	
	
	
	
	
	
	
	
	
	public TextField textFieldProxyAddress;
	
	public TextField textFieldProxyAccount;
	
	public TextField textFieldZhiboProxyAddress;
	
	public TextField textFieldZhiboProxyAccount;
	
	
	public TextField textFieldhgaddress;
	public TextField textFieldhgaccount;
	public TextField textFieldhgpwd;
	public  Button btnlogintohg;
	
	public static boolean blogintohg = false;
	
	public PrintStream psFile = null;
	public PrintStream psConsole = null;
	
	
	
	
	public static Vector<String> mailList = new Vector<String>();
	

	public static String address = "";
	public static String account = "";
	public static String password = "";
	
	
	public static MainWindow mainWnd = new MainWindow();

	
	public static String showtext = "";
	
	
	public static HGPS38EventManager hgps38EventManager = new HGPS38EventManager();
	
	
	public static SettingPane settingPane = new SettingPane();
	
	public static  ReadWriteLock isnteamsLock = new ReentrantReadWriteLock();
	public static Vector<String[]> isnteams = new Vector<String[]>();

	public static  ReadWriteLock sendDatasLock = new ReentrantReadWriteLock();
	public static Vector<SendData> sendDatas = new Vector<SendData>();
	
	//public static boolean blogintohg = false;
	
	//public static void read
	
	public static void main(String[] args){
		
		
		// System.setProperty("org.eclipse.swt.browser.XULRunnerPath","F:\\devTools\\xulrunner-1.9.2.25");

		System.setProperty("org.eclipse.swt.browser.XULRunnerPath","C:\\xulrunner-1.9.2.25\\");
		
	//	betCtrMng = new BetCentralManager();
		
		readloginparams();

		loginFrame();
		
		initMailList();
	}
	
	
	
	public static Vector<String> getMailList(){
		return mailList;
	}
	
	
	public static void initMailList(){
		
		mailList.add("qry0111@163.com");
		
		mailList.add("huangtao198822@163.com");
		
		mailList.add("adiluan@163.com");
		
		mailList.add("qli1071292021@163.com");

		
		mailList.add("tongjigujinlong@126.com");
		
		//mailList.add("2503706418@qq.com");
		
		//mailList.add("2195876152@qq.com");


	}
	
	
	
	
	
	public static void readloginparams(){
		try{
			
			File file = new File("account/" + "hgloginparams.txt");
			
			if(!file.exists()){
				return;
			}

			BufferedReader freader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
			
			String str = "";

			while ((str = freader.readLine()) != null) {
				
				if(str.contains("address")){
					address = str.replace("address:", "");
				}else if(str.contains("account")){
					account = str.replace("account:", "");
				}else if(str.contains("password")){
					password = str.replace("password:", "");
				}

				}
			
			
			
			
			if(null != freader){
				freader.close();
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void saveloginparams(){
		try{
			
			File file = new File("account/" + "hgloginparams.txt");

			if(!file.exists()){

				
				file.createNewFile();
			}
			
			BufferedWriter fwlocal = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"));

			String str = "address:" + address;
			fwlocal.append(str);
			fwlocal.newLine();
			fwlocal.flush();
			
			str = "account:" + account;
			fwlocal.append(str);
			fwlocal.newLine();
			fwlocal.flush();
			
			str = "password:" + password;
			fwlocal.append(str);
			fwlocal.newLine();
			fwlocal.flush();
			
			fwlocal.close();
			
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
	
	
	
	
	
	
	
	public static void loginFrame(){

		try{
			
			final JFrame lFrame = new JFrame("G    v1.0.6");
			
			
			final Container container = lFrame.getContentPane();
			
			container.setLayout(new BorderLayout());

			//lFrame.setLayout(null);

			JPanel p = new JPanel(new GridLayout(3,2));
			
			container.add(p, BorderLayout.NORTH);
			
			
			JLabel pwpanel = new JLabel();
			pwpanel.setText("密码");
			pwpanel.setSize(50, 20);
			
			final JPasswordField pwtxt = new JPasswordField(40);
			
			final JButton btnConfirm = new JButton("确认");
			
			
			pwtxt.addKeyListener(new KeyAdapter(){ 
			      public void keyPressed(KeyEvent e)    
			      {    
			        if(e.getKeyChar()==KeyEvent.VK_ENTER )   //按回车键执行相应操作; 
			        { 
			        	btnConfirm.doClick();
			        } 
			      } 
			    });
			
			pwtxt.setEchoChar('*');
			
			
			BufferedWriter fw = null;  //写	
			BufferedReader reader = null; //读
			
			String pwinfile = null;
			
			
			File dir = new File("data");
			if (dir.exists()) {
			} else {
				dir.mkdirs();
			}
			
			File file = new File("data/" + "pw"
					+ ".conf");
			
			
			if(!file.exists()){
				fw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), "UTF-8"));
				fw.close();
			}else{
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); // 指定读取文件的编码格式，要和写入的格式一致，以免出现中文乱码,
				
				String str = null;
				
				String lastLine = null;
				
				while ((str = reader.readLine()) != null) {

						pwinfile = str;
						
					}
				
			
			}
			
			final String fpw = pwinfile;
			
			

			
			
			
			
			btnConfirm.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					
					String pw = pwtxt.getText();
					
					if(fpw != null && pw.equals(fpw)){
						

						sa = new DecreaseRatioClient();
						
						sa.launchFrame();
						
						lFrame.setVisible(false);
					}else{
						JOptionPane.showMessageDialog(null, "请输入正确的密码,如忘记密码，请联系管理员", "密码错误", JOptionPane.ERROR_MESSAGE);
					}
					
					

					}
				});

			
			p.add(pwpanel);
			p.add(pwtxt);
			p.add(btnConfirm);
			
			lFrame.setLocation(400, 400);
			
			lFrame.setSize(250, 150);

			lFrame.setVisible(true);
			
			lFrame.setResizable(false);
			
			lFrame.addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					System.exit(0);

				}
			});
			
			
		

			sa = new DecreaseRatioClient();
			
			sa.launchFrame();
			
			lFrame.setVisible(false);
			
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		

		
		
		
	}
	
	
	public void saveServerip() {
		try {
			
			File file = new File("data" + "/serverip.txt");
			
			if(!file.exists()){

				
				file.createNewFile();
			}
			
			BufferedWriter fwlocal = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"));

			String str = textFieldProxyAddress.getText();
			fwlocal.append(str);
			fwlocal.flush();
			
			
			fwlocal.close();


			
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public void launchFrame() {
		
		
		if(blogTofile == true) {
			try {
				// 生成路径
				File dir = new File("log");
				if (dir.exists()) {
				} else {
					dir.mkdirs();
				}

				// 把输出重定向到文件
				
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");// 设置日期格式
				
				psFile = new PrintStream("log/" + df.format(new Date())
							+ ".txt");
				
				
				psConsole = System.out;

				System.setOut(psFile);
				System.setErr(psFile);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}
		
		String title = "";
		if(DecreaseRatioClient.useForOriginal==true&&DecreaseRatioClient.bNeg==false) {
			title = "笑傲江湖    v1.0.0";
		}else {
			title = "反投   v1.0.0";
		}

		final JFrame mainFrame = new JFrame(title);

		mainFrame.setLayout(null);
		
		mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

		//mainFrame.add(panel);
		
		mainFrame.setIconImage(Toolkit.getDefaultToolkit().getImage("xajh.png"));
		
        ImageIcon img = new ImageIcon("images/bg.jpg");  
        //要设置的背景图片  
        JLabel imgLabel = new JLabel(img);  
        //将背景图放在标签里。  
        mainFrame.getLayeredPane().add(imgLabel, new Integer(Integer.MIN_VALUE));  
        //将背景标签添加到jfram的LayeredPane面板里。  
        imgLabel.setBounds(0, 0, img.getIconWidth(), img.getIconHeight());  
        
        Container contain = mainFrame.getContentPane();  
        ((JPanel) contain).setOpaque(false);   
        
        
        
        int Xposition = 50;
        int Yposition = 20;
        
        
		JLabel labelDsnProxyAddress = new JLabel("网址:");
		labelDsnProxyAddress.setSize(50, 25);
		labelDsnProxyAddress.setLocation(Xposition, Yposition);
		//labelDsnProxyAddress.setFont(new Font("MS Song", Font.PLAIN, 9));
		

		textFieldProxyAddress = new TextField();
		textFieldProxyAddress.setSize(100, 25);
		textFieldProxyAddress.setLocation(Xposition + 50, Yposition);

		String ipAddr = "124.156.142.169";
		try {
			
			File file = new File("data" + "/serverip.txt");
			
			if(file.exists()){
				BufferedReader freader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
				String str = "";
				if ((str = freader.readLine()) != null) {
					ipAddr = str;
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		textFieldProxyAddress.setText(ipAddr);
		
		JLabel labelDsnProxyAccount = new JLabel("端口:");
		labelDsnProxyAccount.setSize(50, 25);
		labelDsnProxyAccount.setLocation(Xposition, Yposition + 30);
		//labelDsnProxyAccount.setFont(new Font("MS Song", Font.PLAIN, 9));
        
        
		textFieldProxyAccount = new TextField();
		textFieldProxyAccount.setSize(100, 25);
		textFieldProxyAccount.setLocation(Xposition + 50, Yposition + 30);
		textFieldProxyAccount.setText("9873");
        
        
		btnConnect = new JButton("连接服务器");
		btnConnect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				try{
					
					if(connected){
						//showP8 = true;
						mainWnd.setVisible(true);
						mainWnd.setFocusable(true);
						//mainWnd.requestFocus();
						mainFrame.setVisible(false);
						return;
					}
					
					String address = textFieldProxyAddress.getText();
					String port = textFieldProxyAccount.getText();
					
//					NettyClient.HOST = address;
//					NettyClient.PORT = Integer.parseInt(port);
//					
//					if(NettyClient.connect() == false){
//						JOptionPane.showMessageDialog(null,"连接失败！");
//						return;
//					}
					

					ISNNettyClient.HOST = address;
					ISNNettyClient.PORT = 8871;
					
					if(ISNNettyClient.connect() == false){
						JOptionPane.showMessageDialog(null,"连接失败！");
						return;
					}
					
					
//					ISNHGNettyClient.HOST = address;
//					ISNHGNettyClient.PORT = 9872;
//					
//					if(ISNHGNettyClient.connect() == false){
//						JOptionPane.showMessageDialog(null,"连接失败！");
//						return;
//					}
					
					
					connected = true;
					
					saveServerip();
					
					mainFrame.setVisible(false);
					
					mainWnd.setVisible(true);
					
				}catch(Exception ex){
					ex.printStackTrace();
				}
				


			}

			
		});

		btnConnect.setSize(100, 25);
		btnConnect.setLocation(Xposition, Yposition + 60);
	//	btnConnect.setFont(new Font("MS Song", Font.PLAIN, 9));
		
		
		
		


		
		
		
		
		

		
		
		
		btnChangepw = new Button("显示投单");
		
		btnChangepw.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				try{
					
					if(connected == false){
						JOptionPane.showMessageDialog(null,"请先连接服务器");
					}
					
					
					


					
				}catch(Exception ex){
					ex.printStackTrace();
				}
				


			}
		});
		
		btnChangepw.setSize(60, 25);
		btnChangepw.setLocation(Xposition + 360, Yposition + 100);
		
	//	contain.add(btnChangepw);
		
		
		
		


		
		Label labelhgaddress = new Label("ADD:");
		labelhgaddress.setSize(50, 25);
		labelhgaddress.setLocation(Xposition, Yposition + 120);

		textFieldhgaddress = new TextField();
		textFieldhgaddress.setSize(170, 25);
		textFieldhgaddress.setLocation(Xposition + 50, Yposition+ 120);
		//textFieldhgaccount.setText("139.199.162.53");
		
		textFieldhgaddress.setText(address);
		//textFieldhgaccount.setText("127.0.0.1");
		
		
		
        
		
		
		Label labelhgaccount = new Label("账号:");
		labelhgaccount.setSize(50, 25);
		labelhgaccount.setLocation(Xposition, Yposition + 150);

		textFieldhgaccount = new TextField();
		textFieldhgaccount.setSize(100, 25);
		textFieldhgaccount.setLocation(Xposition + 50, Yposition+ 150);
		//textFieldhgaccount.setText("139.199.162.53");
		
		textFieldhgaccount.setText(account);
		//textFieldhgaccount.setText("127.0.0.1");

		Label labelhgpwd = new Label("密码:");
		labelhgpwd.setSize(50, 25);
		labelhgpwd.setLocation(Xposition, Yposition + 30+ 150);
        
        
        
		textFieldhgpwd = new TextField();
		textFieldhgpwd.setSize(100, 25);
		textFieldhgpwd.setLocation(Xposition + 50, Yposition + 30+ 150);
		textFieldhgpwd.setEchoChar('*');
		textFieldhgpwd.setText(password);
		
        
        
		btnlogintohg = new Button("登录");
		btnlogintohg.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
/*				try{
					
					if(blogintohg){
						//showP8 = true;
						
						return;
					}
					
					address = textFieldhgaddress.getText();
					account = textFieldhgaccount.getText();
					password = textFieldhgpwd.getText();
					
					HGbethttp.setLoginParams(address, textFieldhgaccount.getText(), textFieldhgpwd.getText());
					int res = hgbet.login();
					
					if(res == 1){
						blogintohg = true;
						
						
						
						JOptionPane.showMessageDialog(null,"登录成功");
						saveloginparams();
						
						dxqthread = new DXQClientThread();
						dxqthread.start();
						
						
						
					}else{
						blogintohg = false;
						JOptionPane.showMessageDialog(null,"登录失败");
					}
					

					
				}catch(Exception ex){
					ex.printStackTrace();
				}*/
				


			}

			
		});

		btnlogintohg.setSize(60, 25);
		btnlogintohg.setLocation(Xposition, Yposition + 60+ 150);
		
		
		
/*		contain.add(labelhgaddress);
		contain.add(textFieldhgaddress);
		contain.add(labelhgaccount);
		contain.add(textFieldhgaccount);
		contain.add(labelhgpwd);
		contain.add(textFieldhgpwd);
		contain.add(btnlogintohg);*/
		

        
        
		contain.add(labelDsnProxyAddress);
		contain.add(textFieldProxyAddress);
		contain.add(labelDsnProxyAccount);
		contain.add(textFieldProxyAccount);
		contain.add(btnConnect);
		//contain.add(btnhg);
		

		



		mainFrame.setSize(img.getIconWidth(), img.getIconHeight());

		mainFrame.setVisible(true);
		
		mainFrame.setResizable(false);
		
		mainFrame.setLocation(300, 300);

		mainFrame.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				int n = JOptionPane.showConfirmDialog(null, "确认退出吗?", "退出程序",
						JOptionPane.YES_NO_OPTION);
				if (n == JOptionPane.YES_OPTION) {					
					System.exit(0);
				}else{
					System.out.println("inininin");
					mainFrame.setVisible(true);
				}

			}
		});
		
		
	}

	
	
	
	public static void StartEngine() {
		
		
		
/*		if(hgThread != null && !hgThread.getbexit()) {
			JOptionPane.showMessageDialog(null, "停止为完成，请稍后重启", "提示", JOptionPane.ERROR_MESSAGE);
			return;
		}
		
		
		if(ps38Thread != null && !ps38Thread.getbexit()) {
			JOptionPane.showMessageDialog(null, "停止为完成，请稍后重启", "提示", JOptionPane.ERROR_MESSAGE);
			return;
		}*/
		

		
//		serverThread = new ServerThread();
//		
//		serverThread.start();

		bStartEngine = true;
		
		betCtrMng = new BetCentralManager();
		
		betCtrMng.recoverBetlistVecfromefile();
		
		betCtrMng.recoverAllBetlistVecfromefile();
		
		betCtrMng.recoverBetLogVecfromfile();
		
		betCtrMng.recoverSpecialBetlogVecfromefile();
		
		betCtrMng.recoverSpecialBetlistVecfromefile();
		
		startEngineTime = System.currentTimeMillis();

		ps38Thread = new PS38Thread();
		ps38Thread.start();
		
		hgThread = new HGThread();
		hgThread.start();
		
		isnThread = new ISNThread();
		isnThread.start();
		
		betThread = new BetThread();
		betThread.start();
	}

}
